/**
 *
 * Created by mola on 15-12-10.
 */
'use strict';
var restify = require('restify');
var fs = require('fs');
var PasswordGenerator = require('./core/passwordGenerator');

console.log('load config begin');
var server_conf = JSON.parse(fs.readFileSync('config/server.json'));
var server_port = server_conf.port ? server_conf.port : 8080;
console.log('load config end');

var server = restify.createServer({
    name: 'YourPassword',
    version: '1.0.0'
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('/password/:secret/:key', function (req, res, next) {
    res.charSet('utf-8');
    var p = new Promise(function(resolve, reject) {
        let generator = PasswordGenerator(null);
        generator.generatePass(req.params.secret, req.params.key, function (err, result) {
            if (err) {
                reject(err);
            }
            else {
                resolve(result);
            }
        });
    });

    p.then(function(result) {
        res.send({code : 0, result : result});
    }).catch(function(err) {
        res.send({code : 1, error : err});
        next();
    });
});

server.get(/.*/, restify.serveStatic({
    directory: './public',
    default: 'index.html'
}));

server.listen(server_port, function() {
    console.log('%s listening at %s', server.name, server.url);
});
